package com.abu.classes.utils.manager;

import com.abu.common.exception.CRException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author abu
 */
@Component
public class JwtUtils {

    @Value("${jwt.signature}")
    private String signature = null;
    private final Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    /**
     * 获取token
     *
     * @param map    token包含的数据
     * @param second 过期时间(秒)
     * @return
     */
    public String getToken(Map<String, String> map, int second) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, second);
//        将过期时间和playLoad放进去
        JWTCreator.Builder builder = JWT.create().withExpiresAt(instance.getTime());
        map.forEach(builder::withClaim);
//        返回token
        return builder.sign(Algorithm.HMAC256(signature));
    }

    /**
     * 获取token中的信息
     *
     * @param token
     * @return
     */
    public Map<String, String> getInfoFromToken(String token) {
        //        解析token
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(signature))
                .build()
                .verify(token);
        HashMap<String, String> hashMap = new HashMap<>();
        decodedJWT.getClaims().forEach((key, val) -> {
            hashMap.put(key, val.asString());
        });
        return hashMap;
    }

    /**
     * 检验token是否合法
     *
     * @param token
     * @return
     */
    public void verifyToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(signature)).build().verify(token);
        } catch (TokenExpiredException e) {
            logger.error("token令牌已过期：{}", e.getMessage());
            throw new CRException("token令牌已过期，请重新登录",420);
        }catch (AlgorithmMismatchException e){
            logger.error("token算法不一致：{}", e.getMessage());
            throw new CRException("token算法不一致",420);
        }
        catch (InvalidClaimException e){
            logger.error("无效Claim：{}", e.getMessage());
            throw new CRException("无效Claim",420);
        }
        catch (SignatureVerificationException e){
            logger.error("无效签名：{}", e.getMessage());
            throw new CRException("无效签名",420);
        }catch (JWTDecodeException e){
            logger.error("token核对失败：{}", e.getMessage());
            throw new CRException("token核对失败",420);
        }
    }
}
